<?php
/**
 * Контроллер коментириев
 * 
 * Управление коментариями
 * @author Anton Zavidov
 * @package myLiveShop
 */

/**
 * Класс контроллера для управления коментариями
 *
 */
class ControllerComment extends Element{
    
	/**
	 * Констуктор
	 *
	 * @param string $className имя контроллера
	 */
	public function __construct($className=null){
		$this->name='comment';
		parent::__construct($className?$className:__CLASS__);
	}
	/**
	 * Создание
	 *
	 */
	public function save(){
		parent::save();
		if(!Core::mustLogin()) return false;
		$result=$this->model()->save(
			array(
			    ModelComment::F_PARENT_ID  	=> Requestlocal::getInt(ModelComment::F_PARENT_ID),
            	ModelComment::F_USER_ID  	=> Core::user(),
            	ModelComment::F_MODEL_ID  	=> Requestlocal::getInt(ModelComment::F_MODEL_ID),
            	ModelComment::F_MODEL  	    => Requestlocal::getString(ModelComment::F_MODEL),
            	ModelComment::F_CREATED  	=> date('Y-m-d H:i:s'),
            	ModelComment::F_DESCRIPTION => Requestlocal::getString(ModelComment::F_DESCRIPTION),
            	ModelComment::F_LANG_ID  	=> Core::lang()
			),
			Requestlocal::getInt(ModelComment::F_COMMENT_ID,null,'post')
		);
        if(Core::isJSON()) {
            $this->view->result(is_array($result) ? $result : false);
            return;
        }
		if(!is_array($result)){
			Core::eraseRequest();
			Core::redirect(base64_decode(Vars::_(Core::REFERER)),T::_('Saved'));
		}
		else {
			Core::setFormErrors($result);
			Core::saveReferer();
			Core::saveRequest();
			Core::redirect(Core::getReferer(true),T::_('Error'));
		}
	}
	/**
	 * Удаление
	 *
	 */
	public function delete(){
		if(!Core::mustLogin()) return false;
		parent::delete(false);
		$this->findId(true);
		$count_parent=$this->model()->countParent($this->id);///?
		if($this->model()->countParent($this->id)){
		    $this->model()->save(
    			array(
                	ModelComment::F_DESCRIPTION => ModelComment::DELETED,
    			),
    			$this->id
    		);
		}else{
		    $this->model()->delete($this->id);
		}
        if(Core::isJSON()) {
            $this->view->result();
            return true;
        }
		Core::redirect(base64_decode(Vars::_(Core::REFERER)),T::_('Deleted'));
	}
	
	public function deleteComments($model,$model_id){
		if(!Core::mustLogin()) return false;
		L("Удаляем комментарии для ".$model."(".$model_id.")");
		$list = $this->model()->load(
				false,
				array(
					ModelComment::F_COMMENT_ID 
				),
				array(
					"where"=>ModelComment::F_MODEL.'="'.$model.'" AND ' .ModelComment::F_MODEL_ID ."=".$model_id
				)
			);
		foreach ($list as $item){
			$this->id=$item[ModelComment::F_COMMENT_ID];
			$this->delete();
		}
	}
}